package com.ruicar.afs.cloud.apply.admin.manage.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.apply.admin.auth.util.DataAccessUtil;
import com.ruicar.afs.cloud.apply.admin.manage.entity.SysDepartment;
import com.ruicar.afs.cloud.apply.admin.manage.entity.SysDeptAuthRegion;
import com.ruicar.afs.cloud.apply.admin.manage.service.ApplyDepartmentService;
import com.ruicar.afs.cloud.apply.admin.manage.service.ApplyDeptAuthRegionService;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.apply.enums.CarTypeEnum;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: Lee
 * @date: 2020/5/11 19:39
 * @description: 渠道账户体系，部门管理
 * 部门管理，新增加子部门时，显示的新车展业区域、二手车展业区域，是继承自上一级部门的
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/applyDepartment")
public class ApplyDepartmentController {

    private ApplyDepartmentService applyDepartmentService;
    private ApplyDeptAuthRegionService applyDeptAuthRegionService;

    @PostMapping("/getByParentId")
    @ApiOperation(value = "账户体系部门查询")
    public IResponse getByParentId(@RequestParam("parentId") String parentId) {
        List<SysDepartment> departments = applyDepartmentService.list(Wrappers.<SysDepartment>query().lambda()
                .eq(SysDepartment::getParentId, parentId)
                .eq(DataAccessUtil.isAdmin(), SysDepartment::getChannelId, DataAccessUtil.getChannelId())
                .orderByAsc(SysDepartment::getSortOrder));
        for (SysDepartment en : departments) {
            List<SysDeptAuthRegion> newCarRegion = applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda()
                    .eq(DataAccessUtil.isAdmin(), SysDeptAuthRegion::getChannelId, DataAccessUtil.getChannelId())
                    .eq(SysDeptAuthRegion::getDeptId, en.getId()).eq(SysDeptAuthRegion::getBusinessType, CarTypeEnum.newCar));
            en.setNewCarRegion(loadTree(en, newCarRegion, CarTypeEnum.newCar));

            List<SysDeptAuthRegion> oldCarRegion = applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda()
                    .eq(DataAccessUtil.isAdmin(), SysDeptAuthRegion::getChannelId, DataAccessUtil.getChannelId())
                    .eq(SysDeptAuthRegion::getDeptId, en.getId()).eq(SysDeptAuthRegion::getBusinessType, CarTypeEnum.oldCar));
            en.setOldCarRegion(loadTree(en, oldCarRegion, CarTypeEnum.oldCar));
        }

        return new IResponse().setData(setInfo(departments));
    }

    @PostMapping("/getDeptByParentId")
    @ApiOperation(value = "获取")
    public IResponse getDeptByParentId(@RequestParam("parentId") String parentId) {

        List<SysDepartment> departments = applyDepartmentService.list(Wrappers.<SysDepartment>query().lambda()
                .eq(SysDepartment::getParentId, parentId)
                .eq(DataAccessUtil.isAdmin(), SysDepartment::getChannelId, DataAccessUtil.getChannelId())
                .orderByAsc(SysDepartment::getSortOrder));
        for (SysDepartment en : departments) {
            List<SysDeptAuthRegion> newCarRegion = applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda()
                    .eq(DataAccessUtil.isAdmin(), SysDeptAuthRegion::getChannelId, DataAccessUtil.getChannelId())
                    .eq(SysDeptAuthRegion::getDeptId, en.getId()).eq(SysDeptAuthRegion::getBusinessType, CarTypeEnum.newCar));
            en.setNewCarRegion(newCarRegion);

            List<SysDeptAuthRegion> oldCarRegion = applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda()
                    .eq(DataAccessUtil.isAdmin(), SysDeptAuthRegion::getChannelId, DataAccessUtil.getChannelId())
                    .eq(SysDeptAuthRegion::getDeptId, en.getId()).eq(SysDeptAuthRegion::getBusinessType, CarTypeEnum.oldCar));
            en.setOldCarRegion(oldCarRegion);
        }

        return new IResponse().setData(departments);
    }

    @PostMapping("/getDeptByDeptId")
    @ApiOperation(value = "通过deptId 获取新车和二手车授权区域")
    public IResponse getDeptByParentId(@RequestParam("deptId") Long deptId) {

        Map<String, Object> map = new HashMap<>();
        List<SysDeptAuthRegion> newCarRegion = applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda()
                .eq(DataAccessUtil.isAdmin(), SysDeptAuthRegion::getChannelId, DataAccessUtil.getChannelId())
                .eq(SysDeptAuthRegion::getDeptId, deptId).eq(SysDeptAuthRegion::getBusinessType, CarTypeEnum.newCar));

        List<SysDeptAuthRegion> oldCarRegion = applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda()
                .eq(DataAccessUtil.isAdmin(), SysDeptAuthRegion::getChannelId, DataAccessUtil.getChannelId())
                .eq(SysDeptAuthRegion::getDeptId, deptId).eq(SysDeptAuthRegion::getBusinessType, CarTypeEnum.oldCar));

        map.put("newCarRegion", newCarRegion);
        map.put("oldCarRegion", oldCarRegion);
        return new IResponse().setData(map);
    }


    @Transactional
    @PostMapping("/add")
    @ApiOperation(value = "保存部门信息")
    @CacheEvict(value = CommonConstants.USER_CACHE_KEY_PREFIX, allEntries = true)
    public IResponse add(@RequestBody SysDepartment department) {
        applyDepartmentService.saveDepartment(department);
        return new IResponse().setMsg("添加成功");

    }

    @Transactional
    @PostMapping("/edit")
    @ApiOperation(value = "编辑")
    @CacheEvict(value = CommonConstants.USER_CACHE_KEY_PREFIX, allEntries = true)
    public IResponse edit(@RequestBody SysDepartment department) {
        applyDepartmentService.editDepartment(department);
        return new IResponse().setMsg("编辑成功").setData(true);
    }

    @Transactional
    @RequestMapping(value = "/delByIds/{ids}", method = RequestMethod.DELETE)
    @ApiOperation(value = "批量通过id删除")
    @CacheEvict(value = CommonConstants.USER_CACHE_KEY_PREFIX, allEntries = true)
    public IResponse delByIds(@PathVariable Long[] ids) {
        applyDepartmentService.deleteByIds(ids);
        return new IResponse().setMsg("删除成功");
    }

    @Transactional
    @RequestMapping(value = "/delById/{id}", method = RequestMethod.DELETE)
    @ApiOperation(value = "批量通过id删除")
    @CacheEvict(value = CommonConstants.USER_CACHE_KEY_PREFIX, allEntries = true)
    public IResponse delById(@PathVariable Long id) {
        applyDepartmentService.deleteById(id);
        return new IResponse().setMsg("删除成功");
    }

    @PostMapping("/search")
    @ApiOperation(value = "部门名模糊搜索")
    public IResponse searchByTitle(@RequestParam("title") String title) {
        List<SysDepartment> list = applyDepartmentService.findByTitle(title);
        return new IResponse().setData(setInfo(list));
    }

    @PostMapping("/channelSearch")
    @ApiOperation(value = "部门名模糊搜索")
    public IResponse channelSearch(@RequestParam("title") String title) {
        JSONObject user = SecurityUtils.getUser().getUserExtInfo();
        String channel = user.get("channelId").toString();
        Long channelId = Long.valueOf(channel);
        List<SysDepartment> list = applyDepartmentService.channelSearch(title, channelId);
        return new IResponse().setData(setInfo(list));
    }

    public List<SysDepartment> setInfo(List<SysDepartment> list) {
        list.forEach(item -> {
            if (!CommonConstants.PARENT_ID.equals(Long.valueOf(item.getParentId()))) {
                SysDepartment parent = applyDepartmentService.getById(item.getParentId());
                item.setParentTitle(parent.getTitle());
            } else {
                item.setParentTitle("一级部门");
            }
            if(item.getNewCarRegion()!=null){
                item.getNewCarRegion().forEach(it->{
                    if(it.getChildren().size()>0){
                        it.setChecked(null);
                    }
                });
            }
            if(item.getOldCarRegion()!=null){
                item.getOldCarRegion().forEach(it->{
                    if(it.getChildren().size()>0){
                        it.setChecked(null);
                    }
                });
            }
        });

        return list;
    }

    @PostMapping("/loadNewCarRegionData")
    @ApiOperation(value = "加载新车授权区域")
    public IResponse loadNewCarRegionData(@RequestParam("channelId") Long channelId,
                                          @RequestParam("parentCode") Long parentCode,
                                          @RequestParam("deptParentId") Long deptParentId) {
        //取其上级的授权区域
        List<SysDeptAuthRegion> orgAuthorizeRegion = applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda()
                .eq(SysDeptAuthRegion::getParentId, parentCode)
                .eq(SysDeptAuthRegion::getChannelId, channelId)
                .eq(SysDeptAuthRegion::getDeptId, deptParentId)
                .eq(SysDeptAuthRegion::getBusinessType, CarTypeEnum.newCar));
        return new IResponse().setData(orgAuthorizeRegion);
    }

    @PostMapping("/loadOldCarRegionData")
    @ApiOperation(value = "加载二手车授权区域")
    public IResponse loadOldCarRegionData(@RequestParam("channelId") Long channelId,
                                          @RequestParam("parentCode") Long parentCode,
                                          @RequestParam("deptParentId") Long deptParentId) {
        //取其上级的授权区域
        List<SysDeptAuthRegion> orgAuthorizeRegion = applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda()
                .eq(SysDeptAuthRegion::getParentId, parentCode)
                .eq(SysDeptAuthRegion::getChannelId, channelId)
                .eq(SysDeptAuthRegion::getDeptId, deptParentId)
                .eq(SysDeptAuthRegion::getBusinessType, CarTypeEnum.oldCar));
        return new IResponse().setData(orgAuthorizeRegion);
    }

    @PostMapping("/getDeptAuthRegion")
    @ApiOperation(value = "获取部门授权区域信息")
    public IResponse getDeptAuthRegion(@RequestParam("channelId") String channelId, @RequestParam("deptId") Long deptId) {

        List<SysDeptAuthRegion> orgAuthorizeRegion = applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda()
                .eq(SysDeptAuthRegion::getChannelId, channelId)
                .eq(SysDeptAuthRegion::getDeptId, deptId));
        return new IResponse().setData(orgAuthorizeRegion);
    }


    /**
     * 部门编辑，加载树结构
     */
    private List<SysDeptAuthRegion> loadTree(SysDepartment sysDepartment, List<SysDeptAuthRegion> sysDeptAuthRegions, CarTypeEnum type) {

        List<SysDeptAuthRegion> deptRegions = applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda()
                .eq(SysDeptAuthRegion::getChannelId, sysDepartment.getChannelId())
                .eq(SysDeptAuthRegion::getDeptId, sysDepartment.getParentId())
                .eq(SysDeptAuthRegion::getBusinessType, type));

        if (sysDeptAuthRegions != null && sysDeptAuthRegions.size() > 0) {
            for (SysDeptAuthRegion v1 : deptRegions) {
                for (SysDeptAuthRegion v2 : sysDeptAuthRegions) {
                    if (v1.getCode().equals(v2.getCode()) && v2.getIsChecked()) {
                        v1.setChecked(true);
                    }
                }
            }
        }

        Map<String, List<SysDeptAuthRegion>> collect = deptRegions.stream().collect(Collectors.groupingBy(SysDeptAuthRegion::getParentId));
        List<SysDeptAuthRegion> list = collect.get("1");
        if (ObjectUtils.isNotEmpty(list)) {
            list.forEach(en -> forEach(collect, en));
        }
        // 再次遍历一遍数据
        if(list!=null){
            if(list.size()>0){
                // 先查询一遍这个
                List<SysDeptAuthRegion> ol =applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda()
                        .eq(SysDeptAuthRegion::getChannelId, sysDepartment.getChannelId())
                        .eq(SysDeptAuthRegion::getDeptId, sysDepartment.getId())
                        .eq(SysDeptAuthRegion::getBusinessType, type));
                if(ol.size()>0){
                    for(SysDeptAuthRegion li:list){
                        li.setChecked(null);
                        for(SysDeptAuthRegion oli:ol){
                            if(oli.getCode().toString().equals(li.getCode().toString())){
                                li.setChecked(true);
                                break;
                            }
                        }
                    }
                }
            }
        }
        return list;
    }


    private static void forEach(Map<String, List<SysDeptAuthRegion>> collect, SysDeptAuthRegion entity) {
        List<SysDeptAuthRegion> treeMenuNodes = collect.get(entity.getCode());
        if (collect.get(entity.getCode()) != null) {
            //排序
            entity.setChildren(treeMenuNodes);
            entity.getChildren().forEach(t -> {
                forEach(collect, t);
            });
        }
    }


}
